<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    sqlStatusChart: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      chart: null,
      chartData: {}
    }
  },
  created() {
    const sqlStatusChart = this.sqlStatusChart
    for (const i in sqlStatusChart) {
      const item = sqlStatusChart[i]
      this.chartData[item.status.toString()] = item.num
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'right',
          data: ['已回滚', '已暂停', '待执行', '已执行', '已放弃', '执行失败']
        },
        series: [
          {
            name: 'SQL执行状态',
            type: 'pie',
            radius: '66%',
            center: ['40%', '50%'],
            data: [
              { value: this.chartData['-3'], name: '已回滚', itemStyle: { normal: { color: '#9bd598' }}},
              { value: this.chartData['-2'], name: '已暂停', itemStyle: { normal: { color: '#ffd58f' }}},
              { value: this.chartData['-1'], name: '待执行', itemStyle: { normal: { color: '#abd5f2' }}},
              { value: this.chartData['0'], name: '已执行', itemStyle: { normal: { color: '#ab8df2' }}},
              { value: this.chartData['1'], name: '已放弃', itemStyle: { normal: { color: '#e14f60' }}},
              { value: this.chartData['2'], name: '执行失败', itemStyle: { normal: { color: 'red' }}}
            ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    }
  }
}
</script>
